/*
 * Copyright (c) 2025 Industrial Software Feature Database
 */
package com.comac.ins.isfd.service.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.comac.ins.common.core.exception.base.BaseException;
import com.comac.ins.common.core.utils.MapstructUtils;
import com.comac.ins.common.core.utils.StringUtils;
import com.comac.ins.common.mybatis.core.page.PageQuery;
import com.comac.ins.common.mybatis.core.page.TableDataInfo;
import com.comac.ins.isfd.domain.IsfdMetadataBusinessSceneDefinition;
import com.comac.ins.isfd.domain.IsfdMetadataManagement;
import com.comac.ins.isfd.domain.bo.IsfdMetadataBusinessRefDatabaseBo;
import com.comac.ins.isfd.domain.bo.IsfdMetadataBusinessSceneDefinitionBo;
import com.comac.ins.isfd.domain.vo.IsfdMetadataBusinessRefDatabaseVo;
import com.comac.ins.isfd.domain.vo.IsfdMetadataBusinessSceneDefinitionVo;
import com.comac.ins.isfd.domain.vo.IsfdMetadataDatabaseVo;
import com.comac.ins.isfd.domain.vo.IsfdMetadataManagementVo;
import com.comac.ins.isfd.mapper.IsfdMetadataBusinessSceneDefinitionMapper;
import com.comac.ins.isfd.mapper.IsfdMetadataManagementMapper;
import com.comac.ins.isfd.service.IIsfdMetadataBusinessSceneDefinitionService;
import com.comac.ins.system.domain.SysUser;
import com.comac.ins.system.domain.vo.SysUserVo;
import com.comac.ins.system.mapper.SysUserMapper;
import lombok.RequiredArgsConstructor;

/**
 * 元数据管理-业务场景定义Service业务层处理
 *
 * @author Lion Li
 * @date 2024-09-23
 */
@RequiredArgsConstructor
@Service
public class IsfdMetadataBusinessSceneDefinitionServiceImpl implements IIsfdMetadataBusinessSceneDefinitionService {

    @Autowired
    private IsfdMetadataBusinessSceneDefinitionMapper baseMapper;

    @Autowired
    protected IsfdMetadataBusinessRefDatabaseServiceImpl isfdMetadataBusinessRefDatabaseServiceImpl;

    @Autowired
    protected IsfdMetadataDatabaseServiceImpl isfdMetadataDatabaseServiceImpl;

    @Autowired
    private IsfdMetadataManagementMapper isfdMetadataManagementMapper;

    private final SysUserMapper userMapper;

    /**
     * 查询元数据管理-业务场景定义
     *
     * @param id 主键
     * @return 元数据管理-业务场景定义
     */
    @Override
    public IsfdMetadataBusinessSceneDefinitionVo queryById(Long id) {
        // 1. 查询 parentId 为 0 的主业务场景
        LambdaQueryWrapper<IsfdMetadataBusinessSceneDefinition> lqw = new LambdaQueryWrapper<>();
        lqw.eq(IsfdMetadataBusinessSceneDefinition::getId, id);
        lqw.eq(IsfdMetadataBusinessSceneDefinition::getIsDeleted, 0);
        IsfdMetadataBusinessSceneDefinitionVo scene = baseMapper.selectVoOne(lqw);

        if (scene != null) {
            // 查询创建者信息
            if (Objects.nonNull(scene.getCreateBy())) {
                SysUserVo sysUser = userMapper.selectVoOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getUserId, scene.getCreateBy()));
                scene.setCreateByName(sysUser.getUserName());
            }

            // 查询所有场景
            LambdaQueryWrapper<IsfdMetadataBusinessSceneDefinition> lqwc = new LambdaQueryWrapper<>();
            lqwc.eq(IsfdMetadataBusinessSceneDefinition::getIsDeleted, 0);
            lqwc.eq(IsfdMetadataBusinessSceneDefinition::getBusinessTopId, id);
            List<IsfdMetadataBusinessSceneDefinitionVo> allScenes = baseMapper.selectVoList(lqwc);
            allScenes.add(scene);
            // 创建一个映射以方便查找
            Map<Long, IsfdMetadataBusinessSceneDefinitionVo> sceneMap = allScenes.stream()
                .collect(Collectors.toMap(IsfdMetadataBusinessSceneDefinitionVo::getId, allScene -> allScene));

            // 构建树形结构
            for (IsfdMetadataBusinessSceneDefinitionVo allScene : allScenes) {
                if (allScene.getParentId() != 0) {
                    // 将子场景添加到对应的父场景中
                    IsfdMetadataBusinessSceneDefinitionVo parentScene = sceneMap.get(allScene.getParentId());
                    if (parentScene != null) {
                        if (parentScene.getChildren() == null) {
                            parentScene.setChildren(new ArrayList<>());
                        }
                        parentScene.getChildren().add(allScene);
                    }

                    if (Objects.nonNull(allScene.getCreateBy())) {
                        SysUserVo sysUser = userMapper.selectVoOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getUserId, scene.getCreateBy()));
                        allScene.setCreateByName(sysUser.getUserName());
                    }

                    // 查询关联对象
                    List<IsfdMetadataBusinessRefDatabaseVo> refDatabaseList = isfdMetadataBusinessRefDatabaseServiceImpl.selectByChildBusinessId(allScene.getId());
                    List<IsfdMetadataDatabaseVo> databaseVoList = new ArrayList<>();
                    if (CollUtil.isNotEmpty(refDatabaseList)) {
                        String databaseIds = refDatabaseList.stream()
                            .map(refDatabase -> String.valueOf(refDatabase.getDatabaseId()))
                            .collect(Collectors.joining(","));
                        allScene.setDatabaseIds(databaseIds);

                        // 根据数据库ID查询数据库对象
                        for (IsfdMetadataBusinessRefDatabaseVo isfdMetadataBusinessRefDatabaseVo : refDatabaseList) {
                            IsfdMetadataDatabaseVo databaseVo = isfdMetadataDatabaseServiceImpl.queryById(isfdMetadataBusinessRefDatabaseVo.getDatabaseId());
                            if (Objects.nonNull(databaseVo)) {
                                databaseVoList.add(databaseVo);
                            }
                        }
                    }
                    allScene.setDatabaseVoList(databaseVoList);
                }
            }

            // 查询子业务场景
            scene.setChildren(sceneMap.get(scene.getId()) != null ? sceneMap.get(scene.getId()).getChildren() : new ArrayList<>());

        }

        return scene;
    }

    /**
     * 分页查询元数据管理-业务场景定义列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 元数据管理-业务场景定义分页列表
     */
    @Override
    public TableDataInfo<IsfdMetadataBusinessSceneDefinitionVo> queryPageList(IsfdMetadataBusinessSceneDefinitionBo bo, PageQuery pageQuery) {
        // 1. 只查询 parentId 为 0 的业务场景
        LambdaQueryWrapper<IsfdMetadataBusinessSceneDefinition> lqw = buildQueryWrapper(bo);
        lqw.eq(IsfdMetadataBusinessSceneDefinition::getParentId, 0);
        lqw.eq(IsfdMetadataBusinessSceneDefinition::getIsDeleted, 0);

        if (Objects.nonNull(bo.getCreateByName())) {
            lqw.inSql(IsfdMetadataBusinessSceneDefinition::getCreateBy,
                "SELECT user_id FROM sys_user WHERE user_name LIKE '%" + bo.getCreateByName() + "%'");
        }

        pageQuery.setOrderByColumn("create_time");
        Page<IsfdMetadataBusinessSceneDefinitionVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);

        // 2. 查询所有场景
        LambdaQueryWrapper<IsfdMetadataBusinessSceneDefinition> lqwc = new LambdaQueryWrapper<>();
        lqwc.eq(IsfdMetadataBusinessSceneDefinition::getIsDeleted, 0);
        List<IsfdMetadataBusinessSceneDefinitionVo> allScenes = baseMapper.selectVoList(lqwc);

        // 3. 创建一个映射以方便查找
        Map<Long, IsfdMetadataBusinessSceneDefinitionVo> sceneMap = allScenes.stream()
            .collect(Collectors.toMap(IsfdMetadataBusinessSceneDefinitionVo::getId, scene -> scene));

        // 构建树形结构
        for (IsfdMetadataBusinessSceneDefinitionVo scene : allScenes) {
            if (scene.getParentId() != 0) {
                // 将子场景添加到对应的父场景中
                IsfdMetadataBusinessSceneDefinitionVo parentScene = sceneMap.get(scene.getParentId());
                if (parentScene != null) {
                    if (parentScene.getChildren() == null) {
                        parentScene.setChildren(new ArrayList<>());
                    }
                    parentScene.getChildren().add(scene);
                }

                if (Objects.nonNull(scene.getCreateBy())) {
                    SysUserVo sysUser = userMapper.selectVoOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getUserId, scene.getCreateBy()));
                    scene.setCreateByName(sysUser.getUserName());
                }
            }
        }

        // 获取子业务场景和关联对象
        for (IsfdMetadataBusinessSceneDefinitionVo scene : result.getRecords()) {

            if (Objects.nonNull(scene.getCreateBy())) {
                SysUserVo sysUser = userMapper.selectVoOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getUserId, scene.getCreateBy()));
                scene.setCreateByName(sysUser.getUserName());
            }
            // 子业务场景
            scene.setChildren(sceneMap.get(scene.getId()) != null ? sceneMap.get(scene.getId()).getChildren() : new ArrayList<>());

//            // 查询关联对象
//            List<IsfdMetadataBusinessRefDatabaseVo> refDatabaseList = isfdMetadataBusinessRefDatabaseServiceImpl.selectByChildBusinessId(scene.getId());
//            List<IsfdMetadataDatabaseVo> databaseVoList = new ArrayList<>();
//            if (CollUtil.isNotEmpty(refDatabaseList)) {
//                String databaseIds = refDatabaseList.stream()
//                    .map(refDatabase -> String.valueOf(refDatabase.getDatabaseId()))
//                    .collect(Collectors.joining(","));
//                scene.setDatabaseIds(databaseIds);
//
//                // 根据数据库ID查询数据库对象
//                for (IsfdMetadataBusinessRefDatabaseVo isfdMetadataBusinessRefDatabaseVo : refDatabaseList) {
//                    IsfdMetadataDatabaseVo databaseVo = isfdMetadataDatabaseServiceImpl.queryById(isfdMetadataBusinessRefDatabaseVo.getDatabaseId());
//                    if (Objects.nonNull(databaseVo)) {
//                        databaseVoList.add(databaseVo);
//                    }
//                }
//            }
//            scene.setDatabaseVoList(databaseVoList);
        }
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的元数据管理-业务场景定义列表
     *
     * @param bo 查询条件
     * @return 元数据管理-业务场景定义列表
     */
    @Override
    public List<IsfdMetadataBusinessSceneDefinitionVo> queryList(IsfdMetadataBusinessSceneDefinitionBo bo) {
        LambdaQueryWrapper<IsfdMetadataBusinessSceneDefinition> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<IsfdMetadataBusinessSceneDefinition> buildQueryWrapper(IsfdMetadataBusinessSceneDefinitionBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<IsfdMetadataBusinessSceneDefinition> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getParentId() != null, IsfdMetadataBusinessSceneDefinition::getParentId, bo.getParentId());
        lqw.like(StringUtils.isNotBlank(bo.getName()), IsfdMetadataBusinessSceneDefinition::getName, bo.getName());
        lqw.eq(StringUtils.isNotBlank(bo.getDescription()), IsfdMetadataBusinessSceneDefinition::getDescription, bo.getDescription());
        lqw.eq(StringUtils.isNotBlank(bo.getPurpose()), IsfdMetadataBusinessSceneDefinition::getPurpose, bo.getPurpose());
        lqw.eq(bo.getSort() != null, IsfdMetadataBusinessSceneDefinition::getSort, bo.getSort());
        lqw.eq(bo.getIsDeleted() != null, IsfdMetadataBusinessSceneDefinition::getIsDeleted, bo.getIsDeleted());
        return lqw;
    }

    /**
     * 新增元数据管理-业务场景定义
     *
     * @param bo 元数据管理-业务场景定义
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(IsfdMetadataBusinessSceneDefinitionBo bo, Long businessId, Long parentId) {
        bo.setIsDeleted(0L);
        IsfdMetadataBusinessSceneDefinition add = MapstructUtils.convert(bo, IsfdMetadataBusinessSceneDefinition.class);
        validEntityBeforeSave(add);
        if (bo.getParentId() == 0) {
            businessId = add.getId();
        }
        add.setBusinessTopId(businessId);
        boolean flag = baseMapper.insert(add) > 0;
        // 判断是否是子业务场景，子业务场景需要增加业务、要素库关联关系
        if (bo.getParentId() == 0) {
            businessId = add.getId();
        }
        if (bo.getParentId() != null && bo.getParentId() > 0) {
            // 创建关联对象
            if (Objects.nonNull(bo.getDatabaseIds())) {
                String[] databaseIdList = bo.getDatabaseIds().split(",");
                for (String databaseId : databaseIdList) {
                    IsfdMetadataBusinessRefDatabaseBo isfdMetadataBusinessRefDatabaseBo = new IsfdMetadataBusinessRefDatabaseBo();
                    isfdMetadataBusinessRefDatabaseBo.setBusinessId(businessId);
                    isfdMetadataBusinessRefDatabaseBo.setChildBusinessId(add.getId());

                    isfdMetadataBusinessRefDatabaseBo.setDatabaseId(Long.parseLong(databaseId));
                    isfdMetadataBusinessRefDatabaseBo.setBusinessName(bo.getName());
                    isfdMetadataBusinessRefDatabaseBo.setIsDeleted(0L);

                    isfdMetadataBusinessRefDatabaseServiceImpl.insertByBo(isfdMetadataBusinessRefDatabaseBo);
                }
            }
        }

        if (flag) {
            bo.setId(add.getId());

            // 递归插入子节点
            List<IsfdMetadataBusinessSceneDefinitionBo> children = bo.getChildren();
            if (children != null && !children.isEmpty()) {
                for (IsfdMetadataBusinessSceneDefinitionBo child : children) {
                    child.setIsDeleted(0L);
                    child.setParentId(bo.getId());
                    // 递归调用插入子节点
                    insertByBo(child, businessId, bo.getId());
                }
            }
        }
        return flag;
    }

    /**
     * 修改元数据管理-业务场景定义
     *
     * @param bo 元数据管理-业务场景定义
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(IsfdMetadataBusinessSceneDefinitionBo bo) {
        IsfdMetadataBusinessSceneDefinition update = MapstructUtils.convert(bo, IsfdMetadataBusinessSceneDefinition.class);
        validEntityBeforeSave(update);

        // 更新基本信息
        boolean flag = baseMapper.updateById(update) > 0;

        if (flag) {
            // 清除旧的关联关系
            isfdMetadataBusinessRefDatabaseServiceImpl.deleteByChildBusinessId(bo.getId());

            // 更新关联对象
            if (Objects.nonNull(bo.getDatabaseIds())) {

                String[] databaseIdList = bo.getDatabaseIds().split(",");
                for (String databaseId : databaseIdList) {
                    IsfdMetadataBusinessRefDatabaseBo isfdMetadataBusinessRefDatabaseBo = new IsfdMetadataBusinessRefDatabaseBo();
                    isfdMetadataBusinessRefDatabaseBo.setChildBusinessId(bo.getId());
                    isfdMetadataBusinessRefDatabaseBo.setDatabaseId(Long.parseLong(databaseId));
                    isfdMetadataBusinessRefDatabaseBo.setBusinessName(bo.getName());
                    isfdMetadataBusinessRefDatabaseBo.setIsDeleted(0L);

                    isfdMetadataBusinessRefDatabaseServiceImpl.insertByBo(isfdMetadataBusinessRefDatabaseBo);
                }
            }

            // 更新子节点
            deleteById(bo.getId());
            List<IsfdMetadataBusinessSceneDefinitionBo> children = bo.getChildren();
            if (children != null && !children.isEmpty()) {
                for (IsfdMetadataBusinessSceneDefinitionBo child : children) {
                    child.setParentId(bo.getId());
                    // 更新子节点
                    insertByBo(child, bo.getId(), bo.getId());
                }
            }
        }
        return flag;
    }

    public boolean deleteById(Long id) {
        if(Objects.nonNull(id)){
            List<IsfdMetadataManagement> isfdMetadataManagementList = isfdMetadataManagementMapper.selectList(new LambdaQueryWrapper<IsfdMetadataManagement>()
                .eq(IsfdMetadataManagement::getBusinessId, id));
            if(CollUtil.isNotEmpty(isfdMetadataManagementList)){
                throw new BaseException("id为：" + id + "的业务场景不能删除，该业务场景已经导入过业务");
            }
        }
        LambdaQueryWrapper<IsfdMetadataBusinessSceneDefinition> lqw = new LambdaQueryWrapper<>();
        lqw.eq(IsfdMetadataBusinessSceneDefinition::getBusinessTopId, id);

        IsfdMetadataBusinessSceneDefinition updateEntity = new IsfdMetadataBusinessSceneDefinition();
        updateEntity.setIsDeleted(1L);

        // 执行逻辑删除
        boolean flag = baseMapper.update(updateEntity, lqw) > 0;
        return flag;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(IsfdMetadataBusinessSceneDefinition entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除元数据管理-业务场景定义信息
     *
     * @param id      待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidById(Long id, Boolean isValid) {
        if (isValid) {
            if(Objects.nonNull(id)){
                List<IsfdMetadataManagement> isfdMetadataManagementList = isfdMetadataManagementMapper.selectList(new LambdaQueryWrapper<IsfdMetadataManagement>()
                    .eq(IsfdMetadataManagement::getBusinessId, id));
                if(CollUtil.isNotEmpty(isfdMetadataManagementList)){
                    throw new BaseException("id为：" + id + "的业务场景不能删除，该业务场景已经导入过业务");
                }
            }
        }

        LambdaQueryWrapper<IsfdMetadataBusinessSceneDefinition> lqw = new LambdaQueryWrapper<>();
        lqw.eq(IsfdMetadataBusinessSceneDefinition::getId, id);

        IsfdMetadataBusinessSceneDefinition updateEntity = new IsfdMetadataBusinessSceneDefinition();
        updateEntity.setIsDeleted(1L);

        // 执行逻辑删除
        boolean flag = baseMapper.update(updateEntity, lqw) > 0;
        return flag;
    }
}
